package com.horrywu.getgen;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
import cn.domob.android.ads.AdView;

import com.horrywu.getgen.R;

public class MainActivity extends Activity {
	private Button mGet = null;
	private EditText packageNameEt = null;
	private EditText sha1 = null;
	private EditText md5 = null;
	private EditText gen = null;
	private RelativeLayout mBannerLayout = null;
	private String publisherID = "56OJz5y4uNwTW5HCMj";
	private String placementID = "16TLmltlApS_ANUUvs9Y2UHk";
	private View mSelectPackage = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mGet = (Button) findViewById(R.id.mGetBtn);
		packageNameEt = (EditText) findViewById(R.id.packagename);
		packageNameEt.setText("com.horrywu.getgen");
		sha1 = (EditText) findViewById(R.id.sha1);
		md5 = (EditText) findViewById(R.id.md5);
		gen = (EditText) findViewById(R.id.gen);
		mSelectPackage = findViewById(R.id.mSelectPackage);
		mBannerLayout = (RelativeLayout) findViewById(R.id.mBannerLayout);

		mSelectPackage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				selectPackage();
			}
		});

		mGet.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (packageNameEt.getText().toString() == null) {
					Toast.makeText(MainActivity.this, "输入包名", Toast.LENGTH_SHORT).show();
					return;
				}
				getSign(packageNameEt.getText().toString());
			}
		});

		AdView adView = new AdView(this, publisherID, placementID);
		mBannerLayout.addView(adView);
	}

	// 包名组
	String[] infoStrs;

	/**
	 * 选择
	 */
	private void selectPackage() {
		PackageManager pm = this.getPackageManager();
		List<PackageInfo> apps = pm.getInstalledPackages(PackageManager.GET_SIGNATURES);
		infoStrs = new String[apps.size()];
		for (int i = 0; i < apps.size(); i++) {
			infoStrs[i] = apps.get(i).packageName;
		}

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setSingleChoiceItems(infoStrs, 0, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
				packageNameEt.setText(infoStrs[which]);
			}
		});
		builder.show();
	}

	private void getSign(String ttargetname) {
		PackageManager pm = this.getPackageManager();
		List<PackageInfo> apps = pm.getInstalledPackages(PackageManager.GET_SIGNATURES);
		Iterator<PackageInfo> iter = apps.iterator();
		while (iter.hasNext()) {
			PackageInfo packageinfo = iter.next();
			String packageName = packageinfo.packageName;
			if (packageName.equals(ttargetname)) {
				byte[] cert = packageinfo.signatures[0].toByteArray();
				// 将签名转换为字节数组流
				InputStream input = new ByteArrayInputStream(cert);
				// 证书工厂类，这个类实现了出厂合格证算法的功能
				CertificateFactory cf = null;
				try {
					cf = CertificateFactory.getInstance("X509");
				} catch (CertificateException e) {
					e.printStackTrace();
				}
				// X509证书，X.509是一种非常通用的证书格式
				X509Certificate c = null;
				try {
					c = (X509Certificate) cf.generateCertificate(input);
				} catch (CertificateException e) {
					e.printStackTrace();
				}
				String hexString = null;
				try {
					// 加密算法的类，这里的参数可以使MD4,MD5等加密算法
					MessageDigest md = MessageDigest.getInstance("SHA1");
					// 获得公钥
					byte[] publicKey = md.digest(c.getEncoded());
					// 字节到十六进制的格式转换
					hexString = byte2HexFormatted(publicKey);
					sha1.setText(hexString);
					md = MessageDigest.getInstance("MD5");
					// 获得公钥
					publicKey = md.digest(c.getEncoded());
					// 字节到十六进制的格式转换
					hexString = byte2HexFormatted(publicKey);
					md5.setText(hexString);
					gen.setText(GetUtil.getGen(hexString));
				} catch (NoSuchAlgorithmException e1) {
					e1.printStackTrace();
				} catch (CertificateEncodingException e) {
					e.printStackTrace();
				}
				break;
			}
		}
	}

	// 这里是将获取到得编码进行16进制转换
	private static String byte2HexFormatted(byte[] arr) {
		StringBuilder str = new StringBuilder(arr.length * 2);
		for (int i = 0; i < arr.length; i++) {
			String h = Integer.toHexString(arr[i]);
			int l = h.length();
			if (l == 1)
				h = "0" + h;
			if (l > 2)
				h = h.substring(l - 2, l);
			str.append(h.toUpperCase());
			if (i < (arr.length - 1))
				str.append(':');
		}
		return str.toString();
	}
}
